<template>
  <view class="gg-upload-avatar" @tap="choImage">
    <view class="gg-upload-avatar-left">{{label}}</view>
    <view class="gg-upload-avatar-right">
      <image class="gg-upload-avatar-image" :src=" localSrc " mode="aspectFill" @tap.stop="bigImage" :data-src="localSrc"></image>
    </view>
  </view>
</template>
<script>
export default {
  name: "GgUploadAvatar",
  props: {
    label: {
      type: String,
      default: "当前头像"
    },
    // 占位符
    placeholder: {
      type: String,
      default: "请输入"
    },
    //默认输入框
    value: {
      type: [Number, String],
      default: ""
    },
    maxlength: {
      type: [Number, String],
      default: -1
    },
    labelWidth: {
      type: [String, Number],
      default: 0
    },
    layout: {
      type: String,
      default: "row"
    },
    src: {
      type: String,
      default: "",
    }
  },
  data() {
    return {
      localVal: this.value,
      localSrc: this.src,
    };
  },
  watch: {
    value(newVal) {
      this.localVal = newVal;
    },
    src(newVal) {
      this.localSrc = newVal;
    },
  },
  methods: {
    bigImage(src) {
      let srcUrl = src.currentTarget.dataset.src;
      uni.previewImage({
        urls: [srcUrl]
      });
    },
    // 更换头像
    choImage() {
      uni.chooseImage({
        count: 1, // 最多可以选择的图片张数，默认9
        // sizeType : [ 'compressed' ], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
        success: (res) => {
          var per_avatar = res.tempFilePaths[0];
          this.uploadAvatar(per_avatar);
        }
      });
    },
    uploadAvatar: function (tempFilePaths) {
      this.$request.flagUpImg('UC_PERSONAL_AVATAR', {
        filePath: tempFilePaths,
        name: 'xcx_pper_avatar',
        formData: {
          postType: 'update',
          file_name: 'xcx_pper_avatar'
        }
      }).then((resData) => {
        if (resData.status == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success,',
            duration: 1500
          });
          this.localVal = resData.save_url;
          this.localSrc = resData.img_cdn;
          this.$emit('input', this.localVal);
        }
      });
    }
  }
}
</script>
<style>
.gg-upload-avatar {
  position: relative;
  color: #303030;
  display: flex;
  padding: 6px 10px;
  min-height: 45px;
  border-bottom: 1px solid #f1f1f1;
  justify-content: space-between;
  background-color: #fff;
  align-items: center;
}
.gg-upload-avatar-left {
  min-width: 50px;
  padding: 5px 0;
  margin-right: 10px;
}

.gg-upload-avatar-right {
  width: 150px;
  text-align: center;
  justify-content: flex-end;
}
.gg-upload-avatar-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #99999999;
}
</style>